// pages/search/company/company.ts
import { doCompanyList } from '~/api/search'
let isRefresh = false
interface queryForm {
  pageNo: number
  pageSize: number
  keyWord?: string
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    keyWord: '',
    queryForm: {
      pageNo: 1,
      pageSize: 10,
      keyWord: ''
    } as queryForm,
    status: 'loading' as 'loading' | 'loadmore' | 'nomore',
    tableData: [] as any[],
  },
  handDetail(e: any) {
    const dataset = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/shop/detail/detail?id=${dataset.id}`
    })
  },
  handSearch() {
    const { queryForm, keyWord } = this.data
    queryForm.keyWord = keyWord
    this.setData({
      queryForm
    })
    this.onRefresh()
  },
  onRefresh() {
    const { queryForm } = this.data
    queryForm.pageNo = 1
    this.setData({
      status: 'loading',
      tableData: [],
      queryForm
    })
    this.fetchData()
  },
  /**
    * 分页获取数据
    */
  async fetchData() {
    this.setData({
      status: 'loading'
    })
    const { queryForm, tableData } = this.data
    const data = await doCompanyList(queryForm)
    let newData = []
    if (queryForm.pageNo === 1) {
      newData = data.list
    } else {
      newData = [...tableData, ...data.list]
    }
    queryForm.pageNo++
    this.setData({
      tableData: newData,
      queryForm,
      status: queryForm.pageSize === data.list.length ? 'loadmore' : 'nomore'
    })
    if (isRefresh) {
      wx.stopPullDownRefresh();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e: any) {
    this.setData({
      keyWord: e.keyWord,
      queryForm: {
        pageNo: 1,
        pageSize: 10,
        keyWord: e.keyWord
      }
    })
    this.fetchData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    isRefresh = true
    const { queryForm } = this.data
    queryForm.pageNo = 1
    this.setData({
      status: 'loading',
      tableData: [],
      queryForm
    })
    this.fetchData()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.status == 'nomore') return
    this.fetchData()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})